#include "unixhead.h"

#include <workflow/WFFacilities.h>
#include <workflow/WFHttpServer.h>

#include <iostream>
using namespace std;

static WFFacilities::WaitGroup waitGroup(1);

void sighandler(int signum)
{
    cout << "wait group done\n";
    (void)signum;
    waitGroup.done();
}

void process(WFHttpTask * serverTask)
{
    cout << "process function is running\n";
    int state = serverTask->get_state();
    int error = serverTask->get_error();
    cout << "state:" << state << endl;
    switch(state){
    case WFT_STATE_SYS_ERROR:
        fprintf(stderr, "system error: %s\n", strerror(error)); break;
    case WFT_STATE_NOREPLY:
        printf("state is WFT_STATE_NOREPLY\n"); break;
    }

    //接下来是要进行回复
    if(state != WFT_STATE_TOREPLY) {
        printf("error occurs!\n");
        return;
    }
    
    //获取uri, 解析请求
    auto req = serverTask->get_req();
    auto resp = serverTask->get_resp();
    string method = req->get_method();
    string path = req->get_request_uri();
    cout << "path:" << path << endl;

    if(method == "GET" && path == "/login") {
        //读取服务器本地的文件内容
        // /usr/local/nginx/html/postform.html
        int fd = open("/usr/local/nginx/html/postform.html", O_RDONLY);
        char buff[1024] = {0};
        read(fd, buff, sizeof(buff));

        //将文件内容添加到响应的报文体
        resp->append_output_body(buff, strlen(buff));
        //设置响应报文的首部字段
        resp->add_header_pair("Content-Type", "text/html");
        close(fd);//关闭文件描述符
    }
}

int main()
{
    signal(SIGINT, sighandler);

    WFHttpServer server(process);

    //start的返回值监听成功返回值为0
    if(0 == server.start(8888)) {
        waitGroup.wait();
        server.stop();   
    } else {
        cout << "server start error!\n";
    }

    return 0;
}
